package com.itheima.web.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Freeze;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.*;
import com.itheima.vo.*;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.service.mongo.VideoService;
import com.itheima.vo.CommentVo;
import com.itheima.vo.MovementVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.*;

@Component
public class UserManager {

    @DubboReference
    private UserInfoService userInfoService;
    @DubboReference
    private VideoService videoService;
    @DubboReference
    private MovementService movementService;


    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    // 分页查询
    public ResponseEntity findUserInfoByPage(Integer pageNum, Integer pageSize) {
        // 1.调用rpc查询
        PageBeanVo pageBeanVo = userInfoService.findUserInfoByPage(pageNum, pageSize);
        // 取出集合
        List<UserInfo> userInfoList = (List<UserInfo>) pageBeanVo.getItems();
        // 声明一个集合
        List<UserInfoAndStateVo> vos = new ArrayList<>();
        // 对集合进行判空并且遍历
        if (CollectionUtil.isNotEmpty(userInfoList)) {
            for (UserInfo userInfo : userInfoList) {
                // 创建对象并封装
                UserInfoAndStateVo userInfoAndStateVo = new UserInfoAndStateVo();
                // 判断redis中是否存在冻结状态
                if (freezeService.hasKey(userInfo.getId())) { // 有就是冻结
                    userInfoAndStateVo.setUserStatus("2");
                }
                // 封装
                userInfoAndStateVo.setUserInfo(userInfo);
                // 存入集合中
                vos.add(userInfoAndStateVo);
            }
        }
        // 替换掉pageBeanVo中的集合
        pageBeanVo.setItems(vos);
        // 2.返回
        return ResponseEntity.ok(pageBeanVo);
    }

    // 用户详情
    public ResponseEntity findUserInfoById(Long userId) {
        // 1.调用rpc查询
        UserInfo userInfo = userInfoService.findUserInfoById(userId);
        // 创建对象并封装
        UserInfoAndStateVo userInfoAndStateVo = new UserInfoAndStateVo();
        // 判断redis中是否存在冻结状态
        if (freezeService.hasKey(userInfo.getId())) { // 有就是冻结
            userInfoAndStateVo.setUserStatus("2");
        }
        // 封装
        userInfoAndStateVo.setUserInfo(userInfo);
        // 2.返回
        return ResponseEntity.ok(userInfoAndStateVo);
    }

    // 动态列表
    public ResponseEntity findMovementVoByPage(Integer state, Long userId, Integer pageNum, Integer pageSize) {
        // 1.调用rpc查询
        //nt state = Integer.parseInt(states);
        PageBeanVo pageBeanVo = movementService.findMovvementByPage(state, userId, pageNum, pageSize);
        // 2.封装vo
        // 2.1 声明voList
        List<MovementVo> voList = new ArrayList<>();
        // 2.2 获取movementList
        List<Movement> movementList = (List<Movement>) pageBeanVo.getItems();
        // 2.3 遍历movementList
        if (CollectionUtil.isNotEmpty(movementList)) {
            for (Movement movement : movementList) {
                // 创建vo
                MovementVo vo = new MovementVo();
                vo.setUserInfo(userInfoService.findUserInfoById(movement.getUserId()));
                vo.setMovement(movement);
                // 指定动态时间
                vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));

                // 添加到集合
                voList.add(vo);
            }
        }
        // 3.将vo设置到分页对象
        pageBeanVo.setItems(voList);

        // 4.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    // 动态详情
    public ResponseEntity findMovementVoById(String publishId) {
        // 1.调用rpc查询
        Movement movement = movementService.findById(new ObjectId(publishId));

        // 2.封装vo
        // 创建vo
        MovementVo vo = new MovementVo();
        vo.setUserInfo(userInfoService.findUserInfoById(movement.getUserId()));
        vo.setMovement(movement);
        // 指定动态时间
        vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));

        // 3.返回vo
        return ResponseEntity.ok(vo);
    }

    @DubboReference
    private CommentService commentService;

    // 动态评论列表
    public ResponseEntity findCommentVoByPage(String publishId, Integer pageNum, Integer pageSize) {
        // 1.调用rpc查询分页
        PageBeanVo pageBeanVo = commentService.findByPage(new ObjectId(publishId), 2, pageNum, pageSize);
        // 2.封装vo
        // 2.1 声明voList
        List<CommentVo> voList = new ArrayList<>();
        // 2.2 获取commentList
        List<Comment> commentList = (List<Comment>) pageBeanVo.getItems();
        // 2.3 遍历commentList
        if (CollectionUtil.isNotEmpty(commentList)) {
            for (Comment comment : commentList) {
                // 创建vo
                CommentVo vo = new CommentVo();
                vo.setId(comment.getId().toHexString());// 评论id
                UserInfo userInfo = userInfoService.findUserInfoById(comment.getUserId());
                vo.setAvatar(userInfo.getAvatar()); // 评论人头像
                vo.setNickname(userInfo.getNickname()); // 评论人
                vo.setContent(comment.getContent()); // 评论内容
                vo.setCreateDate(DateUtil.formatDateTime(new Date(comment.getCreated()))); // 评论时间

                // 添加到集合
                voList.add(vo);
            }
        }
        // 3.将vo设置到分页对象
        pageBeanVo.setItems(voList);
        // 4.返回分页对象
        return ResponseEntity.ok(pageBeanVo);
    }

    //显示用户发的视频列表
    public ResponseEntity findVideoByUserId(Long userId, Integer pageNum, Integer pageSize) {
        //调用rpc
        PageBeanVo pageBeanVo = videoService.findVideosByUserId(userId, pageNum, pageSize);
        //获取列表
        List<Video> videoList = (List<Video>) pageBeanVo.getItems();
        //初始化VideoVoList
        List<VideoVo> voList = new ArrayList<>();
        //遍历videoList，封装vo
        if (CollectionUtil.isNotEmpty(videoList)) {
            for (Video video : videoList) {
                VideoVo vo = new VideoVo();
                vo.setUserInfo(userInfoService.findUserInfoById(video.getUserId()));
                vo.setVideo(video);
                //放到集合
                voList.add(vo);
            }
        }
        //封装分页对象
        pageBeanVo.setItems(voList);
        //返回结果
        return ResponseEntity.ok(pageBeanVo);
    }

        //复审
    public ResponseEntity reviewMovement(String[] pushIdlist) {

        //遍历调用rpc
        for (String pushId : pushIdlist) {
            //查询movement对象
            Movement movement = movementService.findById(new ObjectId(pushId));//
            movement.setState(1);//改变参数
            movementService.updateState(movement);//回存
        }
        //返回map
        HashMap<String, String> map = new HashMap<>();
        map.put("message","审核通过~");
        return ResponseEntity.ok(map);
    }

    public ResponseEntity rejectedMovement(String[] pushIdlist) {
        //遍历
        for (String pushId : pushIdlist) {
            //获取对象
            Movement movement = movementService.findById(new ObjectId(pushId));
            movement.setState(2);//改变参数
            movementService.updateState(movement);//回存
        }
        //返回map
        HashMap<String, String> map = new HashMap<>();
        map.put("message","审核通过~");
        return ResponseEntity.ok(map);
    }


    @DubboReference
    private FreezeService freezeService;


    // 冻结用户
    public ResponseEntity saveFreeze(Freeze freeze) {
        // 1. 设置用户的冻结状态
        freeze.setUserStatus("1");
        // 2. 取出用户id
        Integer userId = freeze.getUserId();
        // 3. 查询是否含有该用户的冻结信息
        Freeze freezeByUserId = freezeService.findByUserId(userId);
        // 4. 声明返回数据
        String message = "";
        // 5. 判断用户是否存在冻结信息
        if (freezeByUserId == null) { // 没有冻结时间
            // 6. 添加生成冻结时间
            freeze.setCreated(System.currentTimeMillis());
            // 7. 主键自增
            freeze.setId(ObjectId.get());
            // 8. 调用rpc保存
            message = freezeService.saveFreeze(freeze);
        } else { // 有冻结记录
            // 9. 封装
            freezeByUserId.setCreated(System.currentTimeMillis());
            freezeByUserId.setFreezingRange(freeze.getFreezingRange());
            freezeByUserId.setFreezingTime(freeze.getFreezingTime());
            freezeByUserId.setFrozenRemarks(freeze.getFrozenRemarks());
            freezeByUserId.setReasonsForFreezing(freeze.getReasonsForFreezing());
            freezeByUserId.setUserStatus("1");
            // 10. 修改
            message = freezeService.saveFreeze(freezeByUserId);
        }
        System.out.println(message);
        // 11. 声明一个map集合
        Map<String, String> map = new HashMap<>();
        // 12. 添加数据
        map.put("message", message);
        // 13. 取出冻结时间做选择
        freezeService.saveStatus(freeze);
        // 14. 返回数据
        return ResponseEntity.ok(map);
    }

    // 解冻用户
    public ResponseEntity unFreeze(Integer userId, String frozenRemarks) {
        // 1. 根据userId去查询用户的冻结状态信息
        Freeze freeze = freezeService.findByUserId(userId);
        // 2. 取出冻结天数类型
        Integer freezeDay = freeze.getFreezingTime();
        Map<String, String> map = new HashMap<>();
        // 3. 选择
        switch (freezeDay) {
            case 1:
                map.put("message", "冻结3天，自动解冻");
                return ResponseEntity.status(500).body(map);
            case 2:
                map.put("message", "冻结7天，自动解冻");
                return ResponseEntity.status(500).body(map);
            case 3:  // 永久冻结
                map = freezeService.deleteStatus(freezeDay, freeze, frozenRemarks);
                return ResponseEntity.ok(map);
        }
        return null;
    }
}


